﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;


namespace kiosk
{
    public partial class EditButtons : Form
    {

        private List<ListViewItem> m_ListViewItems;
        private Int32 m_groupID;
        private ListViewItem selection;
        private List<ExtItem> m_dupItems;
        private List<ExtItem> items;
        private DataBaseHandler handler;
        private bool changed = false;
        private TypeConverter m_converter = TypeDescriptor.GetConverter(typeof(Font));

        public EditButtons(int gid)
        {
            this.m_groupID = gid;
            InitializeComponent();
            this.m_ListViewItems = new List<ListViewItem>();
            this.listView1.FullRowSelect = true;
            this.listView1.MouseDown += new MouseEventHandler(listView1_MouseDown);
            items = new List<ExtItem>();
            this.handler = new DataBaseHandler();

            #region eventhandllers
            this.exitBtn.Click += new EventHandler(exitBtn_Click); 
            this.deleteBtn.Click +=new EventHandler(deleteBtn_Click);
            this.moveDownBtn.Click +=new EventHandler(moveDownBtn_Click);
            this.moveUpBtn.Click += new EventHandler(moveUpBtn_Click);
            this.SaveTxtBtn.Click +=new EventHandler(SaveTxtBtn_Click);
            this.createNewBtn.Click +=new EventHandler(createNewBtn_Click);
            this.uploadBtn.Click += new EventHandler(uploadBtn_Click);
            
            #endregion







        }

        void listView1_MouseDown(object sender, MouseEventArgs e)
        {
            
            if(this.selection != null)
            {
                this.selection.BackColor = Color.White;
            
            }

            selection = this.listView1.GetItemAt(e.X, e.Y);

            // If the user selects an item in the ListView, display
            // the image in the PictureBox.
            if (selection != null)
            {

                ExtItem temp = (ExtItem)selection.Tag;
                this.txtLabelTxt.Text = temp.ItemText;
                this.previewBtn.Text = temp.ItemText;
                this.previewBtn.Font = (Font)m_converter.ConvertFromString(temp.Font);

                this.selection.BackColor = Color.DimGray;
                this.txtLabelTxt.Font = selection.Font; 

            }

        }



        private void EditButtons_Load(object sender, EventArgs e)
        {
            this.UseWaitCursor = false;
           
            // let populate the list box and the contents 
            try
            {
                this.m_ListViewItems.Clear();
                this.listView1.Items.Clear();
                this.items.Clear();
                DataTable dt = handler.getAllGroupItems(this.m_groupID);


                foreach (DataRow row in dt.Rows)
                {
                    items.Add(new ExtItem());
                    foreach (DataColumn col in dt.Columns)
                    {

                        if (col.ColumnName == "ItemID")
                        {
                            items[items.Count - 1].ItemID = Convert.ToInt32(row[col]);

                        }
                        else if (col.ColumnName == "ItemText")
                        {
                            items[items.Count - 1].ItemText = Convert.ToString(row[col]);

                        }

                        else if (col.ColumnName == "ItemFont")
                        {
                            items[items.Count - 1].Font = Convert.ToString(row[col]);
                        
                        }

                    }


                }
                 
                foreach (ExtItem it in items)
                {

                    this.m_ListViewItems.Add(new ListViewItem());
                    this.m_ListViewItems[this.m_ListViewItems.Count - 1].Text = it.ItemText;
                   
                    
                    // get the font form the database
                     TypeConverter converter = TypeDescriptor.GetConverter(typeof(Font));
                      // Saving Font object as a string
                     // to be fixed
                     Font font = (Font)converter.ConvertFromString(it.Font);
                    this.m_ListViewItems[this.m_ListViewItems.Count - 1].Font = font;
                    this.m_ListViewItems[this.m_ListViewItems.Count - 1].Tag = it;

                }

                this.m_dupItems = new List<ExtItem>(this.items);
                this.listView1.Columns.Add("Button Text");
                
                
                this.listView1.Items.AddRange(this.m_ListViewItems.ToArray());
                this.listView1.AutoResizeColumns(ColumnHeaderAutoResizeStyle.ColumnContent);
                this.listView1.Refresh();




            }
            catch (Exception ex)
            {
                MessageBox.Show("A error has occured" + ex.Message);


            }






        }

        private void SaveTxtBtn_Click(object sender, EventArgs e)
        {

            if(this.txtLabelTxt.Text.Trim() == string.Empty)
            {

                MessageBox.Show("Please enter some lebel text");
                return;
            
            }


            if (this.selection != null)
            {
                this.selection.Text = this.txtLabelTxt.Text.Trim();
                this.previewBtn.Text = this.txtLabelTxt.Text.Trim();
                /*
                 *  IEnumerable<Int32> id = this.items.Where(c => c.ItemText == cboItName).Select(c => c.ItemID);
                    Int32[] itr = id.ToArray<Int32>();
                 * 
                 * */
                ExtItem it;
                it = (ExtItem)this.selection.Tag;
                Int32 itemID = it.ItemID;
                
                foreach (ExtItem itv in items)
                {
                    if (itemID == itv.ItemID)
                    {
                         
                        itv.ItemText = this.selection.Text;
                       
                    }
                     

                }
                

            }


        }

        private void deleteBtn_Click(object sender, EventArgs e)
        {

            if (this.selection != null)
            {

                if (MessageBox.Show("This Will Delete the Button " + selection.Text, "Question", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.OK)
                {


                    
                    ExtItem item = (ExtItem)selection.Tag;
                    Int32 itemid = item.ItemID;
                    this.handler.delItems(itemid);
                    this.updateListView(); 
                  }
            
            }





        }

        private void uploadBtn_Click(object sender, EventArgs e)
        {
            // The button saves the data in the database
            // the linq code in the action
            // the Dupitem has the original items
            /*
                 *  IEnumerable<Int32> id = this.items.Where(c => c.ItemText == cboItName).Select(c => c.ItemID);
                    Int32[] itr = id.ToArray<Int32>();
                 * 
                 * */
             
            try
            {
                for (int i = 0; i < this.m_dupItems.Count; i++)
                {



                    //if (!String.Equals(this.m_dupItems[i].ItemText, this.items[i].ItemText, StringComparison.OrdinalIgnoreCase))
                    //{
                    //    MessageBox.Show(this.m_dupItems[i].ItemText + " Uodated with " + this.items[i].ItemText);
                    //    this.handler.upDateItemText(this.items[i].ItemID, this.items[i].ItemText);

                    //}
                    //if (!String.Equals(this.m_dupItems[i].Font, this.items[i].Font, StringComparison.OrdinalIgnoreCase))
                    //{
                    //    // update the font in the dataBase
                        
                    //    MessageBox.Show(this.m_dupItems[i].Font + " Uodated with " + this.items[i].Font);
                    //    this.handler.upDateItemFont(this.items[i].ItemID, this.items[i].Font);



                    //}

                    this.handler.upDateItemText(this.items[i].ItemID, this.items[i].ItemText);
                    this.handler.upDateItemFont(this.items[i].ItemID, this.items[i].Font);



                }

                    


                MessageBox.Show("Data sucessfully uploaded to the dataBase !!");
                changed = false;

            }
            catch (Exception ex)
            {

                MessageBox.Show("A error has occured" + ex.Message);
            }




        }

        private void moveUpBtn_Click(object sender, EventArgs e)
        {

            // called when a move up button is pressed
            if (selection == null)
            {
                MessageBox.Show("Please select a item from the listbox", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            ExtItem it = (ExtItem)this.selection.Tag;
            Int32 selectedItemID = it.ItemID;
            int index = this.items.IndexOf(it);
            int preIndex = 0;
            try
            {
                if (index != 0)
                {
                    preIndex = index - 1;
                    // update code of the listview
                   
                    //
                    
                    this.handler.interChangeItems(this.items[index].ItemID, this.items[preIndex].ItemID);
                    this.updateListView();                   
                    MessageBox.Show("Items sucessfully interchanged", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);


                }
            }
            catch (Exception ex)
            {

                MessageBox.Show(ex.Message, "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);


            }

        }

        private void moveDownBtn_Click(object sender, EventArgs e)
        {

            // called when move down is called

            if (selection == null)
            {
                MessageBox.Show("Please select a item from the listbox", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            ExtItem it = (ExtItem)this.selection.Tag;
            Int32 selectedItemID = it.ItemID;
            int index = this.items.IndexOf(it);
            int postIndex = 0;
            try
            {
                if (index != (this.m_ListViewItems.Count - 1))
                {
                    postIndex = index + 1;
                    //
                    
                    //
                    this.handler.interChangeItems(this.items[index].ItemID, this.items[postIndex].ItemID);
                    this.updateListView();
                    MessageBox.Show("Items sucessfully interchanged", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);

                }
            }
            catch (Exception ex)
            {

                MessageBox.Show(ex.Message, "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);


            }


        }
        private void updateListView()
        {

            try
            {
                this.m_ListViewItems.Clear();
                this.listView1.Items.Clear();
                this.items.Clear();
                
                
                DataTable dt = handler.getAllGroupItems(this.m_groupID);


                foreach (DataRow row in dt.Rows)
                {
                    items.Add(new ExtItem());
                    foreach (DataColumn col in dt.Columns)
                    {

                        if (col.ColumnName == "ItemID")
                        {
                            items[items.Count - 1].ItemID = Convert.ToInt32(row[col]);

                        }
                        else if (col.ColumnName == "ItemText")
                        {
                            items[items.Count - 1].ItemText = Convert.ToString(row[col]);

                        }

                        else if (col.ColumnName == "ItemFont")
                        {
                            items[items.Count - 1].Font = Convert.ToString(row[col]);

                        }


                    }


                }

                foreach (ExtItem it in items)
                {

                    this.m_ListViewItems.Add(new ListViewItem());
                    this.m_ListViewItems[this.m_ListViewItems.Count - 1].Text = it.ItemText;
                    TypeConverter converter = TypeDescriptor.GetConverter(typeof(Font));
                    // Saving Font object as a string
                    // to be fixed
                    Font font = (Font)converter.ConvertFromString(it.Font);


                   
                    this.m_ListViewItems[this.m_ListViewItems.Count - 1].Font = font;
                    this.m_ListViewItems[this.m_ListViewItems.Count - 1].Tag = it;

                }

                this.listView1.Items.AddRange(this.m_ListViewItems.ToArray<ListViewItem>());


                this.listView1.Refresh();

                }
            catch (Exception ex)
            {

                MessageBox.Show(ex.Message);
            }
        }

        private void createNewBtn_Click(object sender, EventArgs e)
        {
            // Logic for creation of a new button
            /*
             * this.textBox1.Text = String.Empty;
                    // Delete button from the database
                    // Delete a function that deletes the relayed data from the appllication
                    Item item = (Item)selection.Tag;
                    Int32 itemid = item.ItemID;
                    this.handler.deleteAllRelatedItems(itemid);
                    this.items.Remove(item);
                    this.m_dupItems.Remove(item);
                    this.selection = null;
             * */

            if (MessageBox.Show("This Will add an Example label in all the Languages ( please edit those label's )  !!!" , "Question", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.OK)
            {
                try
                {
                    // logic for creating a new button 

                    //MessageBox.Show("This option is under review please contract software vendor !!!!! Mean while if you want to add a new button ");
                    //  
                    //
                    //
                    List<ExtItem> rItem = this.handler.getRelatedItemBtns(this.items[0].ItemID);
                    List<int> group = new List<int>();
                    foreach (Item itv in rItem)
                    {
                        group.Add(this.handler.getGroupIDOnItemID(itv.ItemID));


                    }
                    // only works for three languages
                    DisplayOption option = new DisplayOption();
                    Random rand = new Random(Environment.TickCount);
                    List<List<string>> fontrows = new List<List<string>>();
                    List<string> fonts = new List<string>();
                    List<List<string>> row = new List<List<string>>();
                    List<string> str = new List<string>();
                    string labeltxt = rand.Next().ToString().Trim();
                    str.Add(labeltxt);
                    fonts.Add(option.DefaultFont);
                    List<string> str1 = new List<string>();
                    List<string> font2 = new List<string>();
                    labeltxt = rand.Next().ToString().Trim();
                    str1.Add(labeltxt);
                    font2.Add(option.DefaultFont);
                    List<string> str3 = new List<string>();
                    List<string> font3 = new List<string>();
                    labeltxt = rand.Next().ToString().Trim();
                    str3.Add(labeltxt);
                    font3.Add(option.DefaultFont);
                    row.Add(str);
                    row.Add(str1);
                    row.Add(str3);
                    fontrows.Add(fonts);
                    fontrows.Add(font2);
                    fontrows.Add(font3);
                    this.handler.createitemInGroup(group,row,fontrows);
                   
                    MessageBox.Show("Created Sucessfully !!");
                    this.updateListView();

                }

                catch (Exception ex)
                {
                    MessageBox.Show("Error occured " + ex.Message, "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);

                }

            }




        }

        private void exitBtn_Click(object sender, EventArgs e)
        {
            if(changed)
                if (MessageBox.Show("Please use the upload button to save the changes !! do you want to quit abyway ?") == System.Windows.Forms.DialogResult.OK)
                {
                    this.Close();

                }
                else

                {
                    return;
                
                }
            this.Close();
        }

        private void labelFontBtn_Click(object sender, EventArgs e)
        {

            // the button that saves the button text
            if(this.selection == null){

                MessageBox.Show("Please select an Item !!");
                return;
                 
            }
            fontDialog1.ShowColor = false;
            ExtItem tempItem = (ExtItem)this.selection.Tag;
            if (fontDialog1.ShowDialog() != DialogResult.Cancel)
            {


                Font selectedFont = fontDialog1.Font;
                TypeConverter converter = TypeDescriptor.GetConverter(typeof(Font));
                // Saving Font object as a string
                string fontString = converter.ConvertToString(selectedFont);
                this.txtLabelTxt.Font = selectedFont;
                // update the font in the listview
                this.selection.Font = selectedFont;
                //IEnumerable<ExtItem> id = this.items.Where(c => c.ItemID == tempItem.ItemID);
                //ExtItem[] itr = id.ToArray<ExtItem>();
                foreach (ExtItem itv in items)
                {
                    if (itv.ItemID == tempItem.ItemID)
                    {
                        itv.Font = fontString;
                        MessageBox.Show(itv.Font);
                    }
                }

               
                this.listView1.Refresh();
                


                MessageBox.Show("Font updated...... . \n Dont please use the upload button to upload the update DataBase !!!");


            }






        }

        private void txtLabelTxt_KeyPress(object sender, KeyPressEventArgs e)
        {
            // check if its the enter key update the txt 
            changed = true;
            if (e.KeyChar == (char)13 )
            {


                if (this.selection != null && this.txtLabelTxt.Text.Trim() != String.Empty)
                {
                    this.selection.Text = this.txtLabelTxt.Text;
                    /*
                     *  IEnumerable<Int32> id = this.items.Where(c => c.ItemText == cboItName).Select(c => c.ItemID);
                        Int32[] itr = id.ToArray<Int32>();
                     * 
                     * */
                    ExtItem it;
                    it = (ExtItem)this.selection.Tag;
                    Int32 itemID = it.ItemID;

                    foreach (ExtItem itv in items)
                    {
                        if (itemID == itv.ItemID)
                        {

                            itv.ItemText = this.selection.Text;

                        }


                    }
                }


            
            }


        }

        private void txtLabelTxt_Leave(object sender, EventArgs e)
        {


            if (this.selection != null && this.txtLabelTxt.Text.Trim() != String.Empty)
            {
                this.selection.Text = this.txtLabelTxt.Text;
                /*
                 *  IEnumerable<Int32> id = this.items.Where(c => c.ItemText == cboItName).Select(c => c.ItemID);
                    Int32[] itr = id.ToArray<Int32>();
                 * 
                 * */
                ExtItem it;
                it = (ExtItem)this.selection.Tag;
                Int32 itemID = it.ItemID;

                foreach (ExtItem itv in items)
                {
                    if (itemID == itv.ItemID)
                    {

                        itv.ItemText = this.selection.Text;

                    }


                }
            }


        }

       

      
        
        

      
       

    }

}